<template>
  <div class="distributor-detail">
    <!-- 标题区域 -->
    <div class="title-area">
      <div class="back-button">
        <router-link to="/agent/distributors" class="back-link">
          <i class="fas fa-arrow-left"></i> 返回分销商列表
        </router-link>
      </div>
      <h1>{{ distributor?.name || '分销商详情' }}</h1>
      <button class="edit-btn" @click="handleEdit">
        <i class="fas fa-edit"></i> 编辑
      </button>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载分销商数据中...</p>
    </div>

    <div v-else-if="!distributor" class="error-container">
      <i class="fas fa-exclamation-triangle"></i>
      <p>未找到分销商信息</p>
      <router-link to="/agent/distributors" class="back-btn">返回分销商列表</router-link>
    </div>

    <div v-else class="detail-content">
      <!-- 分销商基本信息卡片 -->
      <div class="info-card">
        <div class="avatar-container">
          <img :src="distributor.avatar" alt="分销商头像" class="distributor-avatar">
          <span class="status-indicator" :class="statusClass"></span>
        </div>
        <div class="info-details">
          <div class="info-header">
            <h2>{{ distributor.name }}</h2>
            <div class="info-tags">
              <span class="status-tag" :class="statusClass">{{ statusText }}</span>
              <span class="level-tag" :class="`level-${distributor.level}`">{{ levelText }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">ID</span>
              <span class="value">{{ distributor.id }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系人</span>
              <span class="value">{{ distributor.contactPerson }}</span>
            </div>
            <div class="info-item">
              <span class="label">账号(纯数字6-11位)</span>
              <span class="value">{{ distributor.phone }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">电子邮箱</span>
              <span class="value">{{ distributor.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">地址</span>
              <span class="value">{{ distributor.address || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">加入日期</span>
              <span class="value">{{ distributor.joinDate }}</span>
            </div>
          </div>
          <div class="commission-row">
            <div class="commission-label">佣金比例</div>
            <div class="commission-value">
              <div class="commission-bar">
                <div class="commission-progress" :style="`width: ${distributor.commissionRate}%`"></div>
                <span class="commission-rate">{{ distributor.commissionRate }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 业绩概览卡片 -->
      <div class="performance-card">
        <h3 class="card-title">业绩概览</h3>
        <div class="performance-tabs">
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'total' }"
            @click="activeTab = 'total'"
          >总计</button>
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'monthly' }"
            @click="activeTab = 'monthly'"
          >本月</button>
        </div>

        <div v-if="activeTab === 'total'" class="performance-stats">
          <div class="stat-item">
            <span class="stat-title">累计销售额</span>
            <span class="stat-value">¥{{ formatNumber(distributor.totalSales) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-title">累计订单数</span>
            <span class="stat-value">{{ formatNumber(distributor.totalOrders) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-title">累计佣金</span>
            <span class="stat-value">¥{{ formatNumber(distributor.totalCommission) }}</span>
          </div>
        </div>

        <div v-else class="performance-stats">
          <div class="stat-item">
            <span class="stat-title">本月销售额</span>
            <span class="stat-value">¥{{ formatNumber(performanceData.monthlySales) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-title">本月订单数</span>
            <span class="stat-value">{{ formatNumber(performanceData.monthlyOrders) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-title">本月佣金</span>
            <span class="stat-value">¥{{ formatNumber(performanceData.monthlyCommission) }}</span>
          </div>
        </div>
      </div>

      <!-- 销售数据图表 -->
      <DistributorSalesChart
        :distributor-id="distributorId"
        title="销售数据趋势"
      />

      <!-- 订单列表 -->
      <div class="orders-section">
        <h3 class="section-title">订单管理</h3>
        <DistributorOrdersList
          :distributor-id="distributorId"
          @view-detail="handleOrderDetail"
        />
      </div>

      <!-- 订单详情模态框 -->
      <div class="order-detail-modal" v-if="orderDetailVisible">
        <div class="modal-backdrop" @click="closeOrderDetail"></div>
        <div class="modal-container">
          <div class="modal-header">
            <h3>订单详情</h3>
            <button class="close-btn" @click="closeOrderDetail">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div class="modal-body" v-if="selectedOrder">
            <div class="info-group">
              <div class="info-item">
                <span class="label">订单编号:</span>
                <span class="value">{{ selectedOrder.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间:</span>
                <span class="value">{{ selectedOrder.orderTime }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单状态:</span>
                <span :class="['status-badge', `status-${selectedOrder.status}`]">
                  {{ getOrderStatusText(selectedOrder.status) }}
                </span>
              </div>
            </div>

            <div class="divider"></div>

            <div class="order-products">
              <h4>商品明细</h4>
              <div class="product-list">
                <div class="product-item" v-for="(product, index) in selectedOrder.products" :key="index">
                  <div class="product-info">
                    <span class="product-name">{{ product.name }}</span>
                    <span class="product-quantity">x{{ product.quantity }}</span>
                  </div>
                  <span class="product-price">¥{{ product.price.toFixed(2) }}</span>
                </div>
              </div>
            </div>

            <div class="divider"></div>

            <div class="order-totals">
              <div class="total-item">
                <span class="label">商品总额:</span>
                <span class="value">¥{{ selectedOrder.totalAmount.toFixed(2) }}</span>
              </div>
              <div class="total-item highlight">
                <span class="label">佣金金额:</span>
                <span class="value">¥{{ selectedOrder.commission.toFixed(2) }}</span>
              </div>
            </div>

            <div class="divider"></div>

            <div class="customer-info">
              <h4>客户信息</h4>
              <div class="info-item">
                <span class="label">客户姓名:</span>
                <span class="value">{{ selectedOrder.customerName }}</span>
              </div>
              <div class="info-item">
                <span class="label">账号(纯数字6-11位):</span>
                <span class="value">{{ selectedOrder.customerPhone }}</span>
              </div>
              <div class="info-item">
                <span class="label">配送地址:</span>
                <span class="value">{{ selectedOrder.deliveryAddress }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付方式:</span>
                <span class="value">{{ selectedOrder.paymentMethod }}</span>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button class="close-btn-secondary" @click="closeOrderDetail">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { generateDistributorDetailData } from '@/utils/agentMock';
import DistributorSalesChart from '@/components/agent/distributors/DistributorSalesChart.vue';
import DistributorOrdersList from '@/components/agent/distributors/DistributorOrdersList.vue';

// 路由相关
const route = useRoute();
const router = useRouter();
const distributorId = computed(() => route.params.id as string);

// 状态管理
const loading = ref(true);
const distributor = ref<any>(null);
const activeTab = ref<'total' | 'monthly'>('total');

// 订单详情状态
const orderDetailVisible = ref(false);
const selectedOrder = ref<any>(null);

// 模拟的月度业绩数据
const performanceData = reactive({
  monthlySales: 0,
  monthlyOrders: 0,
  monthlyCommission: 0
});

// 计算属性
const statusClass = computed(() => {
  if (!distributor.value) return '';
  return `status-${distributor.value.status}`;
});

const statusText = computed(() => {
  if (!distributor.value) return '';
  switch (distributor.value.status) {
    case 'active': return '活跃';
    case 'inactive': return '已停用';
    case 'pending': return '待审核';
    default: return '未知状态';
  }
});

const levelText = computed(() => {
  if (!distributor.value) return '';
  switch (distributor.value.level) {
    case 'standard': return '标准分销商';
    case 'premium': return '高级分销商';
    case 'vip': return 'VIP分销商';
    default: return '未知等级';
  }
});

// 格式化数字
const formatNumber = (num: number) => {
  if (num === undefined || num === null) return '0';
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 处理编辑
const handleEdit = () => {
  // 在实际项目中，这里会打开编辑模态框
  console.log('编辑分销商:', distributor.value);
  // 例如可以导航到编辑页面或打开编辑模态框
};

// 获取数据
const fetchDistributorData = async () => {
  loading.value = true;
  try {
    // 在实际项目中，这里会调用API获取分销商详情
    const data = await generateDistributorDetailData(distributorId.value);
    distributor.value = data;

    // 设置月度数据（模拟）
    performanceData.monthlySales = data.totalSales * (Math.random() * 0.2 + 0.05);
    performanceData.monthlyOrders = Math.floor(data.totalOrders * (Math.random() * 0.2 + 0.05));
    performanceData.monthlyCommission = performanceData.monthlySales * (data.commissionRate / 100);
  } catch (error) {
    console.error('获取分销商详情失败:', error);
    distributor.value = null;
  } finally {
    loading.value = false;
  }
};

// 订单相关方法
const handleOrderDetail = (order: any) => {
  selectedOrder.value = order;
  orderDetailVisible.value = true;
};

const closeOrderDetail = () => {
  orderDetailVisible.value = false;
  setTimeout(() => {
    selectedOrder.value = null;
  }, 300);
};

const getOrderStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待处理';
    case 'processing': return '处理中';
    case 'completed': return '已完成';
    case 'cancelled': return '已取消';
    default: return '未知状态';
  }
};

onMounted(() => {
  fetchDistributorData();
});
</script>

<style lang="scss" scoped>
.distributor-detail {
  padding: 24px;

  .title-area {
    display: flex;
    align-items: center;
    margin-bottom: 24px;

    .back-button {
      margin-right: 16px;

      .back-link {
        color: #4a6cf7;
        text-decoration: none;
        display: flex;
        align-items: center;
        font-size: 14px;

        &:hover {
          text-decoration: underline;
        }

        i {
          margin-right: 6px;
        }
      }
    }

    h1 {
      flex-grow: 1;
      margin: 0;
      font-size: 24px;
      color: #2f3542;
    }

    .edit-btn {
      padding: 8px 16px;
      background-color: #4a6cf7;
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background-color: #3a5bd7;
      }

      i {
        margin-right: 6px;
      }
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px;

    .spinner {
      border: 4px solid rgba(74, 108, 247, 0.2);
      border-top: 4px solid #4a6cf7;
      border-radius: 50%;
      width: 48px;
      height: 48px;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    p {
      color: #6b7280;
      font-size: 16px;
    }
  }

  .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px;

    i {
      font-size: 48px;
      color: #ef4444;
      margin-bottom: 16px;
    }

    p {
      font-size: 18px;
      color: #4b5563;
      margin-bottom: 24px;
    }

    .back-btn {
      padding: 8px 16px;
      background-color: #4a6cf7;
      color: white;
      border: none;
      border-radius: 6px;
      text-decoration: none;
      transition: background-color 0.3s;

      &:hover {
        background-color: #3a5bd7;
      }
    }
  }

  .detail-content {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .info-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    padding: 24px;
    display: flex;

    .avatar-container {
      position: relative;
      margin-right: 24px;
      flex-shrink: 0;

      .distributor-avatar {
        width: 120px;
        height: 120px;
        border-radius: 60px;
        object-fit: cover;
        border: 4px solid #f3f4f6;
      }

      .status-indicator {
        position: absolute;
        bottom: 6px;
        right: 6px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        border: 2px solid white;

        &.status-active {
          background-color: #10b981;
        }

        &.status-inactive {
          background-color: #ef4444;
        }

        &.status-pending {
          background-color: #f59e0b;
        }
      }
    }

    .info-details {
      flex-grow: 1;

      .info-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h2 {
          margin: 0;
          font-size: 20px;
          color: #1f2937;
        }

        .info-tags {
          display: flex;
          gap: 8px;

          .status-tag, .level-tag {
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 500;
          }

          .status-tag {
            &.status-active {
              background-color: rgba(16, 185, 129, 0.1);
              color: #10b981;
            }

            &.status-inactive {
              background-color: rgba(239, 68, 68, 0.1);
              color: #ef4444;
            }

            &.status-pending {
              background-color: rgba(245, 158, 11, 0.1);
              color: #f59e0b;
            }
          }

          .level-tag {
            background-color: rgba(79, 70, 229, 0.1);
            color: #4f46e5;

            &.level-premium {
              background-color: rgba(8, 145, 178, 0.1);
              color: #0891b2;
            }

            &.level-vip {
              background-color: rgba(217, 119, 6, 0.1);
              color: #d97706;
            }
          }
        }
      }

      .info-row {
        display: flex;
        margin-bottom: 16px;

        .info-item {
          flex: 1;
          min-width: 0;

          .label {
            display: block;
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 4px;
          }

          .value {
            font-size: 14px;
            color: #1f2937;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .commission-row {
        margin-top: 24px;

        .commission-label {
          font-size: 14px;
          color: #6b7280;
          margin-bottom: 8px;
        }

        .commission-value {
          .commission-bar {
            position: relative;
            height: 24px;
            background-color: #f3f4f6;
            border-radius: 12px;
            overflow: hidden;

            .commission-progress {
              position: absolute;
              left: 0;
              top: 0;
              height: 100%;
              background-color: #4a6cf7;
              border-radius: 12px;
              transition: width 0.5s;
            }

            .commission-rate {
              position: absolute;
              right: 12px;
              top: 0;
              height: 100%;
              display: flex;
              align-items: center;
              color: white;
              font-weight: 500;
              font-size: 14px;
              text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
            }
          }
        }
      }
    }
  }

  .performance-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    padding: 24px;

    .card-title {
      margin: 0 0 16px 0;
      font-size: 18px;
      color: #1f2937;
    }

    .performance-tabs {
      display: flex;
      margin-bottom: 24px;
      border-bottom: 1px solid #e5e7eb;
      padding-bottom: 8px;

      .tab-btn {
        padding: 8px 16px;
        background: none;
        border: none;
        font-size: 14px;
        color: #6b7280;
        cursor: pointer;
        margin-right: 12px;
        border-radius: 4px 4px 0 0;
        transition: all 0.3s;
        font-weight: 500;

        &:hover:not(.active) {
          background-color: #f9fafb;
        }

        &.active {
          color: #4a6cf7;
          box-shadow: inset 0 -2px 0 #4a6cf7;
        }
      }
    }

    .performance-stats {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 24px;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16px;
        background-color: #f9fafb;
        border-radius: 8px;

        .stat-title {
          font-size: 14px;
          color: #6b7280;
          margin-bottom: 8px;
        }

        .stat-value {
          font-size: 24px;
          color: #1f2937;
          font-weight: 600;
        }
      }
    }
  }

  .orders-section {
    .section-title {
      margin: 0 0 16px 0;
      font-size: 18px;
      color: #1f2937;
    }
  }

  // 订单详情模态框样式
  .order-detail-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .modal-backdrop {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      backdrop-filter: blur(2px);
    }

    .modal-container {
      position: relative;
      width: 90%;
      max-width: 600px;
      max-height: 90vh;
      background-color: white;
      border-radius: 12px;
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      animation: modal-pop 0.3s ease-out;

      @keyframes modal-pop {
        from { transform: scale(0.9); opacity: 0; }
        to { transform: scale(1); opacity: 1; }
      }
    }

    .modal-header {
      padding: 20px;
      border-bottom: 1px solid #e5e7eb;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #1f2937;
      }

      .close-btn {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        border: none;
        background-color: #f3f4f6;
        color: #6b7280;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          background-color: #e5e7eb;
          color: #1f2937;
        }
      }
    }

    .modal-body {
      padding: 20px;
      overflow-y: auto;
      flex: 1;

      .info-group {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 16px;
      }

      .info-item {
        margin-bottom: 12px;

        .label {
          display: block;
          font-size: 14px;
          color: #6b7280;
          margin-bottom: 4px;
        }

        .value {
          font-size: 15px;
          color: #1f2937;
          font-weight: 500;
        }
      }

      .divider {
        height: 1px;
        background-color: #e5e7eb;
        margin: 20px 0;
      }

      .order-products {
        h4 {
          margin: 0 0 12px 0;
          font-size: 16px;
          color: #4b5563;
        }

        .product-list {
          .product-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px dashed #e5e7eb;

            &:last-child {
              border-bottom: none;
            }

            .product-info {
              display: flex;
              align-items: center;

              .product-name {
                font-size: 14px;
                color: #1f2937;
              }

              .product-quantity {
                font-size: 14px;
                color: #6b7280;
                margin-left: 8px;
              }
            }

            .product-price {
              font-size: 14px;
              color: #1f2937;
              font-weight: 500;
            }
          }
        }
      }

      .order-totals {
        .total-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            font-size: 14px;
            color: #6b7280;
          }

          .value {
            font-size: 14px;
            color: #1f2937;
            font-weight: 500;
          }

          &.highlight {
            .label, .value {
              font-size: 16px;
              font-weight: 600;
              color: #4a6cf7;
            }
          }
        }
      }

      .customer-info {
        h4 {
          margin: 0 0 12px 0;
          font-size: 16px;
          color: #4b5563;
        }
      }

      .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 16px;
        font-size: 12px;
        font-weight: 500;

        &.status-pending {
          background-color: rgba(245, 158, 11, 0.1);
          color: #f59e0b;
        }

        &.status-processing {
          background-color: rgba(59, 130, 246, 0.1);
          color: #3b82f6;
        }

        &.status-completed {
          background-color: rgba(16, 185, 129, 0.1);
          color: #10b981;
        }

        &.status-cancelled {
          background-color: rgba(239, 68, 68, 0.1);
          color: #ef4444;
        }
      }
    }

    .modal-footer {
      padding: 16px 20px;
      border-top: 1px solid #e5e7eb;
      display: flex;
      justify-content: flex-end;

      .close-btn-secondary {
        padding: 8px 20px;
        background-color: #f3f4f6;
        color: #4b5563;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          background-color: #e5e7eb;
          color: #1f2937;
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .distributor-detail {
    padding: 16px;

    .title-area {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .back-button {
        margin-right: 0;
      }
    }

    .info-card {
      flex-direction: column;
      padding: 16px;

      .avatar-container {
        align-self: center;
        margin-right: 0;
        margin-bottom: 16px;

        .distributor-avatar {
          width: 100px;
          height: 100px;
        }
      }
    }

    .performance-card {
      padding: 16px;

      .performance-stats {
        grid-template-columns: 1fr;
        gap: 16px;
      }
    }

    .order-detail-modal {
      .modal-container {
        width: 95%;
        max-height: 95vh;
      }

      .modal-body {
        .info-group {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>
